<?php
/**
 * App
 * The basis of your web application! Handles requests, determining controller->action($args).
 *
 * @package Mundy
 */

namespace mundy;

class App {

    protected $request,
              $route,
              $load;

    private   $controller,
              $action,
              $args;

    /**
     * Mundy handles routing & dispatching in a automatted way.
     *
     * @param array $vars Passed to the Load class
     */
    public function __construct( $vars = '' ) {
        $this->request = strtoupper($_SERVER['REQUEST_METHOD']);
        $this->route   = ( isset($_GET['r']) ) ? trim($_GET['r'], '/\\') : 'main';
        $this->load    = new Load($vars);
        
        $this->map()->run();
    }

    /**
     * Map the route to controller, action & args.
     *
     * @return Self
     */
    public function map(  ) {
        $parts = explode(DIRECTORY_SEPARATOR, $this->route);
        $i = 0;

        foreach( $parts as $part ) {
            $this->load->cPath .= $part.'/';
            if( is_dir($this->load->cPath) ) {
                ++$i;
            }
            else break;
        }

        $this->controller = $parts[$i].$this->load->cPostfix;
        $this->action     = ( isset($parts[$i + 1]) ) ? $parts[$i + 1] : $this->request;
        $this->args       = array_slice($parts, $i + 2);

        return $this;
    }

    /**
     * Calls the controller, action & args.
     */
    public function run(  ) {
        $file = trim($this->load->cPath, '/\\').'.php';
        $file = str_replace($this->controller, ucfirst($this->controller), $file);

        if( class_exists($this->controller, false) ) {
            $controller = new $this->controller;
            $controller($this->load);

            if( method_exists($controller, $this->action) ) {
                call_user_func_array(array($controller, $this->action), $this->args);
            }
            else {
                var_dump('Shit! Action not callable: ', $this->action);
            }
        }
        elseif( is_file($file) ) {
            include $file;
            $this->run();
        }
        else var_dump('Shit! Class file not found: ', $file);
    }
}